define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('typeahead');
    require('doctor-data');
    require('fileinput');
    require('daterangepicker');
    require('doctor-select');
    require('moment');
    require('clockpicker');
    require('datetimepicker');
    require('iCheck');
    require('typeahead');

    $.module("DATA.xfrecord", function () {

        return {
            init: function () {
                this.loadData();
                this.loadEvent();
            },
            clearDatas:function () {
                var that = this;

                $("#_id").val(0);
                $("#userwxid").removeAttr('data-id').val('');
                $("#productid").removeAttr('data-id').val('');

                $("#money").val('');
                $("#num").val('');
                $("#createdate").val('');

                $('#fm').bootstrapValidator('resetForm', true);
                that.showDiv('main_div');
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;

                var s_id = $("#s_id").val();
                var s_userwxid = $("#s_userwxid").val();
                var s_money = $("#s_money").val();
                var s_num = $("#s_num").val();

                var s_create_time_begin = $("#s_create_time_begin").val();
                var s_create_time_end = $("#s_create_time_end").val();

                SYS.Core.ajax({
                    url: "data/xfrecord/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        id: s_id || 0,
                        userwxid: s_userwxid || 0,
                        money: s_money || 0,
                        num: s_num || 0,
                        create_time_begin: s_create_time_begin,
                        create_time_end: s_create_time_end
                    },
                    success: function (data) {
                        var obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable").bootstrapTable('destroy');
                        $('#myTable').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                {field: 'checked', checkbox: true} ,
                                {field: 'id', title: '编号', align: 'center'},
                                {field: 'userwxid', title: '头像', align: 'center',
                                    formatter: function (value, row, index) {
                                        if (row.user_info) {
                                            const img = row.user_info.avatarUrl
                                            return SYS.Tool.getUserImg(img)
                                        }
                                    }
                                },
                                {field: 'userwxid', title: '昵称（id）', align: 'center',
                                    formatter: function (value, row, index) {
                                        if (row.user_info) {
                                            const nickname = row.user_info.nickname
                                            return nickname + "(" + value+ ")";
                                        }
                                    }
                                 },
                                {field: 'userwxid', title: '手机号码', align: 'center',
                                    formatter: function (value, row, index) {
                                        if (row.user_info) {
                                            const mobile = row.user_info.mobile
                                            return mobile
                                        }
                                    }
                                },
                                {field: 'money', title: '金额', align: 'center'},
                                {field: 'createdate', title: '消费时间', align: 'center'},
                                {field: 'productid', title: '消费明细', align: 'center',
                                    formatter: function (value, row, index) {
                                        if (row.product_info) {
                                            const productname = row.product_info.productname;
                                            return productname;
                                        }
                                    }
                                },
                                {
                                    field: 'do', title: '操作', align: 'center',
                                    formatter: function (value, row, index) {
                                        var html = '';
                                        html += '<a href="javascript:void(0)" onclick="DATA.xfrecord.toEdit(' + row.id + ')" class="btn btn-edit">编辑</a> | ';
                                        html += '<a href="javascript:void(0)" onclick="DATA.xfrecord.toRemove(' + row.id + ')" class="btn btn-remove  ">删除</a>';
                                        return html;
                                    }
                                }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {
                                that.loadData();
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                // 定义编辑框form
                var $form = $("#fm");

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    that.loadData();
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        that.loadData();
                    }
                });

                // 初始化搜索日期控件
                SYS.Tool.initDaterangSearchWithHHmm('s_create_time', 's_create_time_begin', 's_create_time_end');

                var typeAheadArr = [
                    {id: "s_isuse", data: DOCTOR.Data.common.isuse_status}
                ];
                for (var i in typeAheadArr) {
                    var typeHead = typeAheadArr[i];
                    SYS.Tool.selectTypeahead(typeHead.id, typeHead.data);
                }

                $("#userwxid").on('click', function () {
                    DOCTOR.Select.showUser(this);
                });

                $("#productid").on('click', function () {
                    DOCTOR.Select.showProduct(this);
                });


                //批量删除
                $("#btn_deletes").on('click',function(){
                    that.toRemoves();
                });

                // 绑定日期控件
                $("#createdate").datetimepicker({
                    minView: "hour",
                    format: 'yyyy-mm-dd hh:ii',
                    todayBtn: true,
                    language: 'zh-CN', // 汉化
                    autoclose: true    // 选择日期后自动关闭
                }).on('changeDate', function (ev) {
                    var field = $(this).attr("id");
                    $form.find("input[data-field='" + field + "']").val(ev.date.getTime());
                });

                // 保存新增
                $("#btn_contiune_add").on('click', function () {
                    // 不用关闭当前编辑框
                    that.save(1);
                });

                // 新增
                $("#btn_add").on('click', function () {
                    that.clearDatas();

                    $("#btn-add-div").show();
                    $("#btn-edit-div").hide();
                    that.showDiv('edit_div');
                });

                $("#btn_export").on('click', function () {
                    that.toExport();
                });

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});

                // 返回
                $(".back_list").on('click', function () {
                    that.clearDatas();
                    that.showDiv('main_div');
                });

                //
                $('#fm').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // title: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                        money: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^([1-9](\d*))(\.\d+)?$/i,
                                    message: '金额格式不正确'
                                }
                            }
                        },
                        num: {
                            validators: {
                                notEmpty: {
                                    message: '此项必填'
                                },
                                regexp: {
                                    regexp: /^[1-9]\d*$/i,
                                    message: '数量格式不正确，必须大于0'
                                }
                            }
                        }
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    that.save(0);
                });

            },
            save: function (isContinus) {
                var that = this;

                var id = $("#_id").val();
                var userwxid  =$("#userwxid").attr("data-id");
                var productid = $("#productid").attr("data-id");
                var money = $("#money").val();
                var num = $("#num").val();
                var createdate = $("#createdate").val();

                SYS.Core.ajax({
                    url: 'data/xfrecord/save',
                    common: {},
                    data:{
                        id: id || 0,
                        userwxid: userwxid,
                        productid: productid,
                        money: money,
                        num: num,
                        createdate: createdate  || null
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            if (isContinus) {
                                that.clearDatas();
                                that.loadData();
                                that.showDiv('edit_div');
                            } else {
                                that.loadData();
                                that.showDiv('main_div');
                            }

                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            toEdit: function (id) {
                var that = this;
                that.clearDatas();
                $("#btn-add-div").hide();
                $("#btn-edit-div").show();

                SYS.Core.ajax({
                    url: 'data/xfrecord/detail',
                    common: {},
                    data: {
                        id: id ? id : 0
                    },
                    success: function (data) {
                        if (data.code == 1) {
                            var obj = data.data;

                            let id = obj.id;
                            let userwxid = obj.userwxid;
                            let user_info = obj.user_info;
                            let productid = obj.productid;
                            let product_info = obj.product_info;
                            let money = obj.money;
                            let num = obj.num;
                            let createdate = obj.createdate;

                            $("#_id").val(id);
                            if (user_info) {
                                $("#userwxid").attr("data-id", userwxid).val(user_info.nickname);
                            }

                            if (product_info) {
                                $("#productid").attr("data-id", productid).val(product_info.productname);
                            }

                            $("#money").val(money);
                            $("#num").val(num);
                            $("#createdate").val(createdate);

                            that.showDiv('edit_div');
                        }
                    }
                });
            },
            toRemove: function (id) {
                var that = this;
                $.messager.confirm("确定要删除吗？", function() {
                    SYS.Core.ajax({
                        url: "data/xfrecord/delete",
                        common: {},
                        data: {
                            ids: [id]
                        },
                        success: function (data) {
                            if(data.code == 1){
                                $.messager.popup(data.msg, "success");
                                that.loadData();
                            }else{
                                $.messager.popup(data.msg,'error');
                            }
                        }
                    })
                });
            },
            toRemoves: function () {
                var that = this;
                var selRows = $('#myTable').bootstrapTable('getSelections');
                var delIds = [];
                if(selRows.length > 0){
                    $.each(selRows, function (i, obj) {
                        if(obj.id > 0){
                            delIds.push(obj.id);
                        }
                    });
                    $.messager.confirm("确定批量删除吗？", function() {
                        SYS.Core.ajax({
                            url: "data/xfrecord/delete",
                            common: {},
                            data: {
                                ids: delIds
                            },
                            success: function (data) {
                                if(data.code == 1){
                                    $.messager.popup(data.msg,"success");
                                    that.loadData();
                                }else{
                                    $.messager.popup(data.msg,'error');
                                }
                            }
                        })
                    });
                }else{
                    $.messager.popup('请选择一条记录后再删除','warn');
                }
            },
            initFileinput: function (initialPreview) {
                var options = {
                    img_id: 'img',
                    type_id: 5000,
                    initialPreview: initialPreview,
                    hid_img_id: 'hide_img',
                    showZoom: false
                };
                SYS.Tool.initSingleImg(options);
            },
            toExport: function () {
                var that = this;

                var s_id = $("#s_id").val();
                var s_username = $("#s_username").val();
                var s_mobile = $("#s_mobile").val();
                var s_hxcode = $("#s_hxcode").val();
                var s_isuse = $("#s_isuse").attr('data-id');

                var s_create_time_begin = $("#s_create_time_begin").val();
                var s_create_time_end = $("#s_create_time_end").val();
                var s_hx_time_begin = $("#s_hx_time_begin").val();
                var s_hx_time_end = $("#s_hx_time_end").val();

                var data = {
                    tempmsgid: s_id || 0,
                    username: s_username,
                    mobile: s_mobile,
                    hxcode: s_hxcode,
                    isuse: s_isuse,
                    create_time_begin: s_create_time_begin,
                    create_time_end: s_create_time_end,
                    hx_time_begin: s_hx_time_begin,
                    hx_time_end: s_hx_time_end
                };

                var parameters = JSON.stringify({
                    common:{},
                    data: data
                });

                $.messager.confirm('确定要导出吗？', function () {
                    window.open( '/data/xfrecord/exportData?parameters=' + encodeURI(parameters));
                });
            },
            showDiv: function (div) {
                var divs = ['main_div','edit_div','import_div'];
                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });

    DATA.xfrecord.init();
});